package com.yunlinker.asba.aliupload;

import android.util.Log;

import com.alibaba.sdk.android.oss.common.auth.OSSFederationCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.ResponseStream;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yunlinker.asba.networkcallback.UrlApi;
import org.json.JSONObject;

//import okhttp3.OkHttpClient;
//import okhttp3.Request;
//import okhttp3.Response;

/**
 * Created by Administrator on 2015/12/9 0009.
 * 重载OSSFederationCredentialProvider生成自己的获取STS的功能
 */
public class STSGetter extends OSSFederationCredentialProvider {

    private String stsServer = "http://jke5.com/swzh/api/imgupload/app/getUploadToken";

    public STSGetter() {
        stsServer = UrlApi.UPLOAD_URL;
    }

    public STSGetter(String stsServer) {
        this.stsServer = stsServer;
    }

    public OSSFederationToken getFederationToken() {

        HttpUtils http = new HttpUtils() ;
        http.configCurrentHttpCacheExpiry(1000 * 10); //设置超时时间
        try {
            ResponseStream responseStream = http.sendSync(HttpRequest.HttpMethod.GET,
                    stsServer ,
                    null ) ;
            //int statusCode = responseStream.getStatusCode();
            //Header[] headers = responseStream.getBaseResponse().getAllHeaders();
            String s = responseStream.readString();
            try {
                JSONObject jsonObjs = new JSONObject(s);
                String ak = jsonObjs.getString("AccessKeyId");
                String sk = jsonObjs.getString("AccessKeySecret");
                String token = jsonObjs.getString("SecurityToken");
                String expiration = jsonObjs.getString("Expiration");
                return new OSSFederationToken(ak, sk, token, expiration);
            }
            catch (Exception e) {
                Log.e("GetSTSTokenFail", e.toString());
                e.printStackTrace();
                return null;
            }
        } catch (Exception e) {

            return null;
        }

//        String stsJson;
//        OkHttpClient client = new OkHttpClient();
//        Request request = new Request.Builder().url(MainApplication.ALiUpLoadToken).build();
//        try {
//            Response response = client.newCall(request).execute();
//            if (response.isSuccessful()) {
//                stsJson = response.body().string();
//            } else {
//                throw new IOException("Unexpected code " + response);
//            }
//        }
//        catch (Exception e) {
//            e.printStackTrace();
//            Log.e("GetSTSTokenFail", e.toString());
//            return null;
//        }



    }

}
